'use strict'
let AppID = 'wx56840cO9ca9a9e39'
let AppSecret = 'b2636c62ab152eb835e2b91033fde99f'
let access_token = ''
let openid = ''
class timeletter{

  constructor (mdb) {
    this.mdb = mdb || null
  }
  async get(){
    let sql='select * from timeletter'
    let r=await this.mdb.query(sql)
    let timeletter=r['rows'];
    return timeletter
  }


  async insert(d) {

    let login_url=`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=`
    + AppID + '&secret=' + AppSecret
        let result=await gohttp.get(login_url)
        let r=result.json()
        openid=r.openid
        if(r.openid===undefined){
            c.status(500)
            return
        }

        let info={
            openid:r.openid,
            expires:7200000,
            timestamp:Date.now(),
            random:Math.random()
        }
        
        access_token=c.helper.aesEncrypt(JSON.stringify(info),c.service.tokenKey)



    //
    let requestData = {
      "touser": openid,
      "template_id": "tyT9WPxkv1J38yXfCLxs9nHt4HyVXaKHV7CJfwqMBZo",
      "page": "index",
      "lang": "zh_CN",
      "data": {
          "times": {
              "value": "2020-12-10 12:12:12"
          },
          "name1": {
              "value": "刘小豆"
          },
          "thing4": {
              "value": "提醒你看时光信"
          }
      }
    }
  //
  // 2、发送模板消息
  let res = await request
  .post(`https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=${access_token}`)
  .send(requestData)
  .set('Accept', 'application/json')
  console.log(res)







    console.log(JSON.parse(d))
    
    let sql='select * from timeletter'
    let r=await this.mdb.query(sql)
    let letterid=r['rows'].length+1;
    let data=JSON.parse(d)
     
    this.mdb.connect().then(client=>{
      client.query('insert into timeletter values($1::int,$2::timestamp,$3::int,$4::int,$5::text,$6::varchar,$7::varchar,$8::int)',[letterid,data.lettertime,data.themeid,data.backimgid,data.content,'免费',data.lettertcolor,data.lettertstyleid]).then(res=>{
        
      })
    })
    return access_token
  }
 
}

module.exports = timeletter
